package org.jfk.core.controller;

import java.util.HashMap;
import java.util.Map;

import org.jfk.core.utils.e189id.ByteFormat;
import org.jfk.core.utils.e189id.HMACSHA1;
import org.jfk.core.utils.e189id.XXTea;

import com.jfinal.kit.PropKit;

public class E189IdController extends BaseController {
	
	private final static String appId = PropKit.get("e189.id.appId");
	private final static String appSecret = PropKit.get("e189.id.appSecret");
	private final static String returnURL = PropKit.get("e189.id.returnURL");
	private final static String authURL = PropKit.get("e189.id.authURL");
	
	public void getSign() throws Exception{
		
		
		
		String timeStamp = ""+System.currentTimeMillis();
		
		String plainText = "timeStamp="+timeStamp+"&returnURL="+returnURL;
		String cipherText = 
				XXTea.encrypt(plainText,"UTF-8",ByteFormat.toHex(appSecret.getBytes()));		
		System.out.println(cipherText);

		String clientType = "20100";
		String format = "redirect";
		String version = "v1.1";
		String paras = cipherText;

		String pText = XXTea.decrypt(cipherText,"UTF-8",ByteFormat.toHex(appSecret.getBytes()));
		System.out.println(pText);		
		
		String plainSig = appId+clientType+format+version+paras;
		String sign = HMACSHA1.getSignature(plainSig,appSecret).toUpperCase();
		System.out.println("sign:"+ sign);
		
		String authUrl = authURL;
		
		authUrl += "?appId="+appId
				+ "&clientType="+clientType
				+ "&format="+format
				+ "&version="+version
				+ "&paras="+paras
				+ "&sign="+sign
				+ "&timeStamp="+timeStamp
				+ "&returnURL="+returnURL; 
		System.out.println(authUrl);
		
		Map map = new HashMap();
		map.put("sign", sign);
		map.put("paras", paras);
		map.put("queryStr", plainText);
		map.put("authUrl", authUrl);
		
		this.renderJson(map);
	}
	
	public void userInfo() throws Exception{

		String rtnAppId = getPara("appId");
		String paras = getPara("paras");
		String sign = getPara("sign");

		String pText = XXTea.decrypt(paras,"UTF-8",ByteFormat.toHex(appSecret.getBytes()));
		
		String[] s = pText.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0 ; i < s.length ; i++){
			String[] ss = s[i].split("=");
			if (ss.length > 1){
				map.put(ss[0],ss[1]);
			}
		}
		
		this.renderJson(map);
	}
}
